﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EventHub.Data.DataModel;

namespace EventHub.Data.DataAccess
{
    public class EventHubModelDataAdapter
    {
        private EventHubModelContainer _modelContainer;

        public EventHubModelDataAdapter()
        {
            string connectionString = "metadata=res://*/DataModel.EventHubModel.csdl|res://*/DataModel.EventHubModel.ssdl|res://*/DataModel.EventHubModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=devsql05;Initial Catalog=SACSSIS;Integrated Security=True;MultipleActiveResultSets=True'";
            _modelContainer = new EventHubModelContainer(connectionString);
        }
        


        public string[] GetMatchingEvents(string eventText)
        {
            return _modelContainer.SACBusinessEvent.Where(be => be.EventName.Contains(eventText)).Select(be => be.EventName).ToArray();
        }

        public SACBusinessEvent LoadEventTree(string eventName)
        {
            var eventItems = _modelContainer.SACBusinessEvent.Where(be => be.EventName == eventName);
            SACBusinessEvent parentRootEvent = null;
            if (eventItems.Count() > 0)
            {
                var eventItem = eventItems.First();
                parentRootEvent = GetRootParent(eventItem);
                LoadEventTree(parentRootEvent);
            }
            return parentRootEvent;
        }

        public void LoadEventTree(SACBusinessEvent eventItem)
        {
            eventItem.ChildEvents.Load();
            if (eventItem.ChildEvents.Count() > 0)
            {
                foreach (var childItem in eventItem.ChildEvents)
                {
                    LoadEventTree(childItem);
                }
            }
        }

        private SACBusinessEvent GetRootParent(SACBusinessEvent businessEvent)
        {
            businessEvent.ParentEvents.Load();
            SACBusinessEvent parentEvent = businessEvent;
            if (parentEvent.ParentEvents.Count() > 0)
            {
                return GetRootParent(parentEvent.ParentEvents.First());
            }
            else
            {
                parentEvent = businessEvent;
            }
            return parentEvent;
        }
    }
}
